import Vue from "vue";

import loading from "./loading.vue";

let LoadingConstructor = Vue.extend(loading);

let instance;

let close_status = false;

let timer = null;

//设置自动关闭时长
const TIME = 8 * 1000;

const Loading = (options = {}) => {
	let target = "";
	close_status = false;

	if (instance) {
		removeChild();
	}

	instance = new LoadingConstructor({
		data: options,
	});

	//loading插入的目标元素
	target = options.target || document.body;

	instance.$mount();

	target.appendChild(instance.$el);

	options.autoClose && autoClose(options.autoCloseDuration);

	return instance;
};

Loading.close = function () {
	close_status = true;

	removeChild();
};

function removeChild() {
	if (instance) {
		instance.$el.parentNode.removeChild(instance.$el);
		instance = null;
	}
}

//未关闭则自动关闭
function autoClose(autoCloseDuration) {
	clearTimeout(timer);

	timer = setTimeout(() => {
		if (!close_status) {
			Loading.close();
		}
	}, autoCloseDuration || TIME);
}

export default Loading;
